<template>
	<statusBarVue title="接单偏好" :isShowBar="true" :isShowLeft="true" :isMyBgi="true" />
	<view class="order-page" :style="pageHaveBarStyle">
		<view class="order-page-group">
			<view class="order-page-item" v-for="(v,i) in orderList" :key="'order-page-item-'+i">
				<uni-icons class="icon-s" type="settings-filled" size="30" @click="openPriceInp(v)"></uni-icons>
				<view class="item-block">
					<view>工作地址：<text>{{v.addr}}</text></view>
					<view>工作时长：<text>{{ toolConvertMinutesToTime(v.ranging, 'ranging')}}</text></view>
					<view>工作时间：
						<text>{{ toolConvertMinutesToTime(v.starting_hour)}}</text>~<text>{{ toolConvertMinutesToTime(v.ending_hour)}}</text>
					</view>
				</view>
			</view>
		</view>
		<view class="order-page-group add-btns">
			<button style="color:#ffffff;backgroundColor:#22A366;" @click="openPriceInp()">新增接单偏好</button>
		</view>
	</view>


	<uni-popup ref="orderPpopup" type="bottom" borderRadius="16px 16px 0 0" safeArea backgroundColor="#F3F3F5">
		<view class="order-popup">
			<view class="order-popup-h">
				<view class="tit">
					编辑
				</view>
				<button class="close" @click="close">
					<uni-icons type="closeempty"></uni-icons>
				</button>
			</view>
			<view class="order-popup-b">
				<uni-forms :model="formData" label-width="120px" ref="orderForm" :rules="rules">
					<uni-forms-item label="工作地点" name="addr" required>
						<picker mode="region" :value="formData.addr" @change="e=>this.formData.addr=e.detail.value">
							<view class="picker-value">
								{{ (Array.isArray(formData.addr)) ? (formData.addr).join('') : '请选择工作地点' }}
							</view>
						</picker>
					</uni-forms-item>
					<uni-forms-item label="工作开始时间" name="starting_hour" required>
						<picker mode="time" :value="formData.starting_hour"
							@change="onChangeTime('starting_hour',$event)" :end="formData.ending_hour">
							<view class="picker-value">
								{{ formData.starting_hour ? formData.starting_hour : '请选择工作开始时间' }}
							</view>
						</picker>
					</uni-forms-item>
					<uni-forms-item label="工作截至时间" name="ending_hour" required>
						<picker mode="time" :value="formData.ending_hour" :start="formData.starting_hour"
							@change="onChangeTime('ending_hour',$event)">
							<view class="picker-value">
								{{ formData.ending_hour ? formData.ending_hour : '请选择工作截至时间' }}
							</view>
						</picker>
					</uni-forms-item>
					<uni-forms-item name="ranging" label="工作时长">
						<view style="line-height: 36px;">
							{{ rangingToString(formData.ranging) }}
						</view>
					</uni-forms-item>
				</uni-forms>

				<view class="footer">
					<button class="btn btn-no" @click="close">取消</button>
					<button class="btn" type="warn" @click="handleDel" v-if="this.formData.id">删除</button>
					<button class="btn btn-yes" @click="handleOk">确认</button>
				</view>
			</view>
		</view>
	</uni-popup>
</template>

<script>
	import statusBarVue from '@/components/statusBar.vue';
	import {
		getPreference,
		postEditPreference,
		postDelPreference
	} from '@/utils/api.js';
	import {
		publics
	} from '@/mixins/publics.js';
	export default {
		mixins: [publics],
		components: {
			statusBarVue
		},
		data() {
			return {
				formData: {
					ranging:'0:0'
				},
				orderPpopupData: {},
				orderList: [],
				rules: {
					addr: {
						rules: [{
							required: true,
							errorMessage: '工作地点不能为空',
						}]
					},
					starting_hour: {
						rules: [{
							required: true,
							errorMessage: '工作开始时间不能为空',
						}]
					},
					ending_hour: {
						rules: [{
							required: true,
							errorMessage: '工作结束时间行不能为空',
						}]
					}
				}
			}
		},
		created() {
			this.getPreferenceApi()
		},
		methods: {
			// 请求 list 
			getPreferenceApi() {
				getPreference().then(res => {
					if (res.code === 200) {
						this.orderList = res.data.preferences
					}
				})
			},
			
			rangingToString(arr){
				let str = "", rangingArr = (this.formData?.ranging).split(':');
				if(Array.isArray(rangingArr)){
					str = `${rangingArr[0]}小时 ${rangingArr[1]}分钟`;
				}else{
					str = '0小时 0分钟'
				}
				return str;
			},

			// 根据传入分钟数 返回 几时 几分
			toolConvertMinutesToTime(minutes, type) {
				// 计算小时
				const hours = Math.floor(minutes / 60);
				let remainingMinutes = (minutes % 60);
				// 计算剩余的分钟数
				if(type === 'ranging'){
					return `${hours}小时 ${remainingMinutes}分钟`;
				}else{
					remainingMinutes = (minutes % 60) < 10 ? '0' + (minutes % 60) : (minutes % 60);
					return `${hours}:${remainingMinutes}`;
				}
			},


			// 选择时间
			onChangeTime(keyName, e) {
				this.formData[keyName] = e.detail.value;

				if (this.formData.starting_hour && this.formData.ending_hour) {
					let duration = this.toolCalculateWorkDuration(this.formData.starting_hour, this.formData.ending_hour);
					this.formData.ranging = duration;
				}
			},

			// 计算时间范围
			toolCalculateWorkDuration(startTime, endTime) {

				if (startTime === undefined && endTime === undefined) {
					return
				}

				// 格式: "HH:MM"
				const startParts = startTime.split(':');
				const endParts = endTime.split(':');

				// 将时间转换为分钟数
				const startMinutes = parseInt(startParts[0]) * 60 + parseInt(startParts[1]);
				const endMinutes = parseInt(endParts[0]) * 60 + parseInt(endParts[1]);

				// 计算时长（分钟）
				let durationMinutes = endMinutes - startMinutes;

				// 计算小时和分钟
				const hours = Math.floor(durationMinutes / 60);
				const minutes = durationMinutes % 60;

				return `${hours}:${minutes}`;
			},

			// 打开弹框
			openPriceInp(item) {
				this.$refs.orderPpopup.open('bottom');
				if(item){
					let {id,addr, starting_hour, ending_hour, ranging} = {...item}
					this.formData = {
						id,
						addr: addr.split(", "),
						starting_hour: this.toolConvertMinutesToTime(starting_hour),
						ending_hour: this.toolConvertMinutesToTime(ending_hour),
						ranging: this.toolConvertMinutesToTime(ranging),
					};
				}
			},

			// 时间格式转换 时 转 分
			toolHourToM(time) {
				let minute = 0;
				// 格式: "HH:MM"
				const timeArr = time.split(':');
				minute = parseInt(timeArr[0]) * 60 + parseInt(timeArr[1]);
				return minute;
			},

			// 关闭弹框
			close() {
				this.$refs.orderPpopup.close();
				this.formData = {ranging:'0:0'}
				this.getPreferenceApi()
			},

			// 删除请求
			postDelPreferenceApi(id) {
				postDelPreference(id).then(res => {
					if (res.code === 200) {
						this.close();
						this.getBankcardsListApi();
					}
				})
			},

			handleDel() {
				uni.showModal({
					title: '提示',
					content: '您确定要删除此条数据吗？',
					success: (res) => {
						if (res.confirm) {
							this.postDelPreferenceApi(this.formData.id)
						}
					}
				});
			},

			handleOk() {
				this.$refs.orderForm.validate((err, formData) => {
					if (!err) {
						let {id, addr, starting_hour, ending_hour, ranging} = {...this.formData}
						let postEditPreferenceData = {id, addr, starting_hour, ending_hour, ranging};

						postEditPreferenceData.starting_hour = this.toolHourToM(postEditPreferenceData
							.starting_hour);
						postEditPreferenceData.ending_hour = this.toolHourToM(postEditPreferenceData.ending_hour);
						postEditPreferenceData.ranging = this.toolHourToM(postEditPreferenceData.ranging);
						postEditPreferenceData.addr = (postEditPreferenceData.addr).join(', ');
						console.log("postEditPreferenceData --------->>>", postEditPreferenceData)
						postEditPreference(postEditPreferenceData).then(res => {
							if (res.code === 200) {
								this.formData = {ranging:'0:0'};
								uni.showToast({
									title: '操作成功！',
									success: (res) => {
										this.close();
									}
								});
							}
						})
					}
				});
			}
		}
	}
</script>

<style lang="scss">
	.order-page {
		position: fixed;
		left: 0;
		right: 0;
		background-color: #F2F3F7;
		padding: 10px 2.66vw;
		box-sizing: border-box;
		z-index: 99;
		
		&-group {
			.order-page-item {
				padding: 10px 12px;
				background-color: #fff;
				box-sizing: border-box;
				border-radius: 12px;
				font-size: 16px;
				position: relative;
				border: 2px solid #22a366;
				margin-bottom: 12px;

				text {
					font-size: 18px;
					font-weight: bold;
				}

				.item-block {
					view {
						margin-top: 10px;
					}
				}

				.icon-s {
					position: absolute;
					top: 14px;
					right: 14px
				}
			}
		}
	}


	.order-popup {
		background: #fff;
		border-radius: 16px 16px 0 0;
		padding: 14px 16px;

		&-h {
			width: 100%;
			height: 27px;
			line-height: 27px;
			display: flex;
			justify-content: space-between;
			align-items: center;

			.tit {
				font-weight: bold;
				font-size: 18px;
				color: #131315;
				height: 50px;
				line-height: 50px;
				display: flex;
			}

			.close {
				width: 16px;
				height: 16px;
				line-height: 16px;
				border-radius: 100%;
				color: #9A9FB3;
				margin: initial;
				padding: 0;
				text-align: center;
			}
		}

		&-b {
			padding: 14px 0;


			uni-picker,
			picker {
				height: 30px;
				background-color: #f7f6f6;
				border: 1px solid #e5e5e5;

				.picker-value {
					height: 30px;
					line-height: 30px;
				}
			}


			.footer {
				margin-top: 24px;
				overflow: hidden;
				display: flex;
				justify-content: space-between;

				.btn {
					padding: 0 24px;
					height: 45px;
					border-radius: 8px;

					&::after {
						border: none;
					}

					&-no {
						color: #22A366;
						background-color: #F5F6FA;
					}

					&-yes {
						color: #fff;
						background-color: #22A366;
					}
				}
			}

		}
	}
</style>